package com.xwj.service.Impl;

import com.xwj.dao.RaRoleDao;
import com.xwj.entity.RaRole;
import com.xwj.service.Interface.RaRoleService;
import com.xwj.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by thinkjoy on 2017/7/12.
 */
@Slf4j
@Service
@CacheConfig(cacheNames = "RaRoleCache")
public class RaRoleServiceImpl implements RaRoleService {

    @Autowired
    private RaRoleDao raRoleDao;

    public static RaRoleServiceImpl getInstance() {
        return SpringUtils.getBean(RaRoleServiceImpl.class);
    }

    @Override
    @Cacheable(key = "#root.methodName")
    public List<RaRole> findAllRole() {
        return raRoleDao.findAllRole();
    }

    @Override
    @Cacheable(key = "'role_'+#id")
    public RaRole findRoleById(int id) {
        try {
            return raRoleDao.findRoleById(id);
        } catch (Exception e) {
            log.error("RaRoleService异常:", e);
            return null;
        }
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int deleteRoleById(int id) {
        try {
            return raRoleDao.deleteRoleById(id);
        } catch (Exception e) {
            log.error("RaRoleService异常:", e);
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int addRole(String name, String desc) {
        try {
            RaRole raRole = new RaRole(name, desc);
            raRoleDao.addRole(raRole);
            return raRole.getId();
        } catch (Exception e) {
            log.error("RaRoleService异常:", e);
            return 0;
        }
    }

}
